/*--------------------------------------------------------------
 * File: SD_card.c 编码类型：C语言  UTF-8
 * Author WRS (1352509846@qq.com)
 * 功能: SD卡驱动功能
 * Version 0.1
 * Date 2024-11-25 
 * 
 * @copyright Copyright (c) 2024
 * 
----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "myDebug.h"
#include "SD_card.h"

#define pin_CS 4
#define pin_MOSI 23
#define pin_MISO 19
#define pin_CLK 18
 
#define MOUNT_POINT "/SD"
const char mount_point[] = "/SD";

uint8_t SD_flag = 0;

void sdcard_init(void)
{
    esp_err_t ret;

	sdmmc_host_t host=SDSPI_HOST_DEFAULT();
	host.slot=SPI2_HOST;
	spi_bus_config_t bus_cnf={
		.mosi_io_num = pin_MOSI,
        .miso_io_num = pin_MISO,
        .sclk_io_num = pin_CLK,
		.quadhd_io_num=-1,  //这行不能省略
		.quadwp_io_num=-1,  //这行不能省略
		.max_transfer_sz=400000,
	};
	spi_bus_initialize(host.slot,&bus_cnf,SPI_DMA_CH_AUTO);
	static sdspi_device_config_t slot_cnf={
		.gpio_cs=pin_CS,
		.gpio_cd=SDSPI_SLOT_NO_CD, //这行不能省略
		.gpio_int=GPIO_NUM_NC,//这行不能省略
		.gpio_wp=GPIO_NUM_NC,//这行不能省略
		.host_id=SPI2_HOST,
    };
	sdmmc_card_t *card;
	esp_vfs_fat_sdmmc_mount_config_t mount_cnf={
		.format_if_mount_failed=true,
		.max_files=5,
		.allocation_unit_size=16*1024,
	};
	ret = esp_vfs_fat_sdspi_mount(mount_point,&host,&slot_cnf,&mount_cnf,&card);
    
    if(ret!=ESP_OK)
    {
        SD_flag = SD_STATE_ERROR;
        MY_ERROR("Failed to initialize the card!");
        return;
    }
    else
    {
        SD_flag = SD_STATE_READY;        
        MY_INFO("Card initialized. OK");
        sdmmc_card_print_info(stdout,card);        
    }	
}

